package com.rp.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.oracle.tools.packager.Log;
import com.rp.admin.serivce.CategoryService;
import com.rp.news.common.PagedResult;
import com.rp.news.common.RedisCommon;
import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.common.Result;
import com.rp.news.util.RedisOperator;
import com.rp.pojo.Category;
import com.rp.vo.SaveOrUpdateCategoryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@Api(value = "文章分类维护相关接口", tags = {"文章分类维护相关接口 api文档"})
@RequestMapping("/categoryMng")
public class CategoryMngController {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    public RedisOperator redis;

    @Autowired
    public RestTemplate restTemplate;


    @ApiOperation(value = "新增或者修改文章分类", notes = "新增或者修改文章分类", httpMethod = "POST")
    @PostMapping("/saveOrUpdateCategory")
    public Result saveOrUpdateFriendLink(@RequestBody @Valid SaveOrUpdateCategoryVo vo) {
        log.info("新增或者修改文章分类,请求参数 vo = {}",JSONUtil.toJsonStr(vo));
        // id为空新增，不为空修改
        if (vo.getId() == null) {
            // 查询新增的分类名称不能重复存在
            boolean isExist = categoryService.queryCatIsExist(vo.getName(), null);
            if (isExist) {
                // 新增到数据库
                Category category = Convert.convert(Category.class, vo);
                categoryService.createCategory(category);
            } else {
                return Result.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        } else {
            // 查询修改的分类名称不能重复存在 false : 存在 ; true: 不存在
            boolean isExist = categoryService.queryCatIsExist(vo.getName(), vo.getOldName());
            if (isExist) {
                // 修改到数据库
                Category category = Convert.convert(Category.class, vo);
                categoryService.modifyCategory(category);
            } else {
                return Result.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        }
        return Result.ok();
    }

    @ApiOperation(value = "查询文章分类列表", notes = "查询文章分类列表", httpMethod = "POST")
    @PostMapping("/getCatList")
    public Result getCatList() {
        List<Category> resutl = categoryService.getCatList();
        log.info("查询文章分类列表,返回结果 resutl = {}",JSONUtil.toJsonStr(resutl));
        return Result.ok(resutl);
    }

    @ApiOperation(value = "用户端查询分类列表", notes = "用户端查询分类列表", httpMethod = "GET")
    @GetMapping("/getCats")
    public Result getCats() {
        log.info("用户端查询分类列表");
        String catString = redis.get(RedisCommon.REDIS_ALL_CATEGORY);
        List<Category> result = new ArrayList<>();
        if (StrUtil.isNotBlank(catString)) {
            result = Convert.convert(new TypeReference<List<Category>>() {
            }, catString);
        } else {
            //先从redis中查询 如果有则返回 如果没有查询数据库之后保存到redis后返回
            result = categoryService.getCatList();
            redis.set(RedisCommon.REDIS_ALL_CATEGORY, JSONUtil.toJsonStr(result));
        }
        return Result.ok(result);
    }
}
